package cn.tedu.charging.order.context.consumer;

import cn.tedu.charging.common.constant.ChargingTopicConstants;
import cn.tedu.charging.common.pojo.vo.ChargingProgressVO;
import cn.tedu.charging.common.pojo.vo.WebSocketMessage;
import cn.tedu.charging.order.context.MqttContext;
import cn.tedu.charging.order.server.WebSocketServer;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

@Slf4j
public class MqttConsumer implements MqttCallbackExtended {
    private MqttContext mqttContext;
    private MqttClient mqttClient;

    public MqttConsumer(MqttContext mqttContext, MqttClient mqttClient) {
        this.mqttContext = mqttContext;
        this.mqttClient = mqttClient;
    }

    /*
     * 连接丢失 处理逻辑
     */
    @Override
    public void connectionLost(Throwable cause) {
        log.error("客户端连接丢失",cause);
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.info("消费者接受消息,主题:{},消息:{}",topic,message.toString());
        if (topic!=null&&topic.equals(ChargingTopicConstants.CHARGING_PROGRESS_TOPIC)){
            WebSocketServer webSocketServer = mqttContext.getWebSocketServer();
            WebSocketMessage<ChargingProgressVO> webSocketMessage = new WebSocketMessage<>();
            webSocketMessage.setState(3);
            webSocketMessage.setMessage("充电进度");
            ChargingProgressVO vo=new ChargingProgressVO();
            vo.setHours(0);
            vo.setMinutes(1);
            vo.setSeconds(0);
            vo.setTotalCost(5.7);
            vo.setChargingCapacity(56.00);
            vo.setTotalCapacity(100.00);
            vo.setOneElectricityCost(0.5);
            webSocketMessage.setData(vo);
            webSocketServer.pushMessage(JSON.toJSONString(webSocketMessage),24);
            log.debug("同步充电进度");
        }
    }
    /*
     * 消费者消息投递结束的处理逻辑
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info("投递消息消费完成");
    }

    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        try{
            mqttClient.subscribe("/aaa");
            mqttClient.subscribe(ChargingTopicConstants.CHARGING_PROGRESS_TOPIC);
            mqttClient.subscribe(ChargingTopicConstants.PILE_CALLBACK_TOPIC);
        }catch (Exception e){
            log.error("连接完成 但是订阅失败",e);
        }
        log.info("连接完成");
    }
}
